package com.yhd.rabbit.tx;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author yhd
 * @createtime 2021/1/24 23:29
 * rabbitmq事务
 */
@Component
public class MqTx {

    private static final String EXCHANGE = "exchange.tx";
    private static final String QUEUE = "queue.tx";
    private static final String ROUTING_KEY = "routing.tx";

    @Resource
    private RabbitTemplate rabbitTemplate;


    //@Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 发送消息
     * @return
     */
    public boolean sendMessage() {

        transactionTemplate.execute(transactionStatus -> {
            rabbitTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, "rabbitmq-tx");
            return rabbitTemplate.receiveAndConvert();
        });
        return true;
    }

    /**
     * 接收消息
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(bindings =
    @QueueBinding(
            value = @Queue(value = QUEUE, autoDelete = "false", durable = "true"),
            exchange = @Exchange(value = EXCHANGE, autoDelete = "true", durable = "true"),
            key = {ROUTING_KEY}
    )
    )
    public void receiveMessage(String msg, Message message, Channel channel) {
        try {
            channel.txSelect();
            System.out.println("msg = " + msg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            channel.txCommit();
        } catch (IOException e) {
            try {
                channel.txRollback();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}